package br.com.ArquivoPadrao.view;

import br.com.ArquivoPadrao.exception.PojoException;
import br.com.ArquivoPadrao.pojo.impl.ArquivoPadraoPojoImpl;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Pricipal extends javax.swing.JFrame {

    int totalInt;
    static File file;
    static File file2;
    
    public Pricipal() {
        initComponents();
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        selArquivoTXT = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        saveArquivoTXT = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        dataTXT = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        qtdRegTXT = new javax.swing.JTextField();
        totalTXT = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("UNICRED CAMPINAS");

        jLabel2.setText("Arquivo Padrão 1.0");

        jLabel3.setText("Selecione o Arquivo:");

        jButton1.setText("Localizar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                localizarBT(evt);
            }
        });

        jLabel4.setText("Salvar Arquivo Em:");

        jButton2.setText("Salvar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salvarBT(evt);
            }
        });

        jLabel5.setText("Data de Lançamento:");

        dataTXT.setText("AAMMDD");
        dataTXT.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dataTXTActionPerformed(evt);
            }
        });

        jLabel6.setText("Quantidade de Registros:");

        jLabel7.setText("Valor Total:");

        jButton3.setText("Processar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                processarBT(evt);
            }
        });

        jButton4.setText("Ajuda");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ajudaBT(evt);
            }
        });

        jButton5.setText("Fechar");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FecharBT(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel2)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(selArquivoTXT))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1))
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(saveArquivoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, 271, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton2))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel5)
                            .addComponent(jLabel7)
                            .addComponent(jLabel6))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(qtdRegTXT)
                            .addComponent(dataTXT, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(totalTXT, javax.swing.GroupLayout.Alignment.LEADING))
                        .addGap(112, 112, 112)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(selArquivoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveArquivoTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(qtdRegTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(dataTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(totalTXT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton4)
                    .addComponent(jButton5))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void salvarBT(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_salvarBT
         JFileChooser ch = new JFileChooser();  
                    int ret = ch.showOpenDialog(Pricipal.this);  
                      
                    if(ret == JFileChooser.APPROVE_OPTION){  
                        file2 = ch.getSelectedFile(); 
                    }
                    String caminho = file2.getPath();     
                    saveArquivoTXT.setText(caminho);
    }//GEN-LAST:event_salvarBT

    private void dataTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dataTXTActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dataTXTActionPerformed

    private void localizarBT(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_localizarBT
        JFileChooser ch = new JFileChooser();  
                    int ret = ch.showOpenDialog(Pricipal.this);  
                      
                    if(ret == JFileChooser.APPROVE_OPTION){  
                        file = ch.getSelectedFile(); 
                        //selArquivoTXT = file;
                    }
                    String caminho = file.getPath();     
                    selArquivoTXT.setText(caminho);
    }//GEN-LAST:event_localizarBT

    private void ajudaBT(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ajudaBT
       
    }//GEN-LAST:event_ajudaBT

    private void processarBT(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processarBT
         try // LEIA SOBRE http://www.guj.com.br/articles/13  
        {             
            FileWriter writer = new FileWriter(file2); // INFORMAR CAMINHO A SER GRAVADO  
            PrintWriter saida = new PrintWriter(writer);  
            BufferedWriter bw = new BufferedWriter(writer);  
            //InputStream is = new InputStream(); // CONVERTE OS DADOS PARA CARACTERES  
            InputStreamReader isr = new InputStreamReader(System.in);  
            BufferedReader br = new BufferedReader(isr);  
             
            //******************   LEITURA CAMPOS/REGRAS DE NEGOCIO HEADER   ******************
            
            //CONVERTE DATA TXT PARA STRING
            String dataS= dataTXT.getText().toString();  
            //CONVERTE TOTAL de REGISTROS PARA INTEIRO E ATRIBUI OS "0"
            int totalQtdI = Integer.parseInt(qtdRegTXT.getText());
            String totalQtdS;
            if (totalQtdI <= 9){
               totalQtdS = ("000"+ qtdRegTXT.getText().toString());
            } else if(totalQtdI > 9 && totalQtdI <=99){
               totalQtdS = ("00"+ qtdRegTXT.getText().toString());
            } else if(totalQtdI > 99 && totalQtdI <=999){
               totalQtdS = ("0"+ qtdRegTXT.getText().toString());
            } else {
               totalQtdS = (qtdRegTXT.getText().toString());
            } 
            
            //CONVERTE o total geral e acrescenta os "0"
            int totalI = Integer.parseInt(totalTXT.getText());
            String totalS = (totalTXT.getText().toString());
            int totalCaracter = Integer.toString(totalI).length();

            while(totalCaracter < 16){     
                totalS = "0"+totalS;
                totalCaracter ++;
            }
            totalS = totalS.replace(",", "");
            
            
           saida.println(dataS + totalQtdS + "000000000" +totalS); 
           
            //******************   LÊ O ARQUIVO IMPORTADO   ******************
            
         FileReader reader = new FileReader(file); // Localização do Arquivo  
         BufferedReader leitor = new BufferedReader(reader);  
         StringTokenizer st = null;  
         String linha = null; 
         
         String ccS;         // Armazena campo de conta corrente  
         String tipoLancS;      // Armazena campo de tipo de lançamento 
         String numDocS;        // Armazena campo do numero do documento  
         String valorS;          // Armazena campo do valor do documento  

  
         while ((linha = leitor.readLine()) != null) {  
                                            
              
            // UTILIZA DELIMITADOR ; PARA DIVIDIR OS CAMPOS  
            st = new StringTokenizer(linha, ";");  
            String dados = null;  
  
            while (st.hasMoreTokens()) {  
  
               // Campo CC  
               dados = st.nextToken();  
               ccS = dados;  
                 
               // Campo Tipo de Lançamento  
               dados = st.nextToken();  
               tipoLancS = dados;  
                 
               // Campo Numero do Documento  
               dados = st.nextToken();  
               numDocS = dados;  
                 
               // Campo Valor do Documento 
               dados = st.nextToken();  
               valorS = dados.replace(",", "");
               
                
               
       //******************   REGRAS DE NEGÓCIO CORPO ARQUIVO   ****************** 
               
               // **** NUMERO DA CONTA ****
               int totalCaracterCC = ccS.length();
               while(totalCaracterCC < 7){     
                ccS = "0"+ccS;
                totalCaracterCC ++;
            }
               
               // **** TIPO LANÇAMENTO ****
               int totalCaracterTL = tipoLancS.length();
               while(totalCaracterTL < 3){     
                tipoLancS = "0"+tipoLancS;
                totalCaracterTL ++;
            }
               
               // **** NUMERO DO DOCUMENTO ****
               int totalCaracterND = numDocS.length();
               while(totalCaracterND < 9){     
                numDocS = "0"+numDocS;
                totalCaracterND ++;
            }
               
               // **** VALOR DO DOCUMENTO ****
               int totalCaracterVD = valorS.length();
               while(totalCaracterVD < 16){     
                valorS = "0"+valorS;
                totalCaracterVD ++;
            }
              
               //Imprimi o Corpo do arquivo
               saida.println(ccS + tipoLancS + numDocS + valorS + dataS);
            }
         }
               
           //******************   REGRAS DE NEGÓCIO CORPO ARQUIVO   ******************
                   
           
            //ESCREVE O HEADER E CORPO DO ARQUIVO
            //saida.println(dataS + totalQtdS + "000000000" +totalS+"\n");   
        
            br.close();  
            bw.close();  
            saida.close();  
            writer.close();  
        }  
                  
        catch(IOException iox)  
        {  
            iox.printStackTrace();  
        }         
      
        new Pricipal();    
    
    }//GEN-LAST:event_processarBT

    private void FecharBT(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FecharBT
        dispose();
    }//GEN-LAST:event_FecharBT

    public static void main(String args[]) {
        Pricipal pricipal = new Pricipal();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Pricipal().setVisible(true);
                
            }
        });
    }
  
    
    public JTextField getDataTXT() {
        return dataTXT;
    }

    public void setDataTXT(JTextField dataTXT) {
        this.dataTXT = dataTXT;
    }

    public JButton getjButton1() {
        return jButton1;
    }

    public void setjButton1(JButton jButton1) {
        this.jButton1 = jButton1;
    }

    public JButton getjButton2() {
        return jButton2;
    }

    public void setjButton2(JButton jButton2) {
        this.jButton2 = jButton2;
    }

    public JButton getjButton3() {
        return jButton3;
    }

    public void setjButton3(JButton jButton3) {
        this.jButton3 = jButton3;
    }

    public JButton getjButton4() {
        return jButton4;
    }

    public void setjButton4(JButton jButton4) {
        this.jButton4 = jButton4;
    }

    public JLabel getjLabel1() {
        return jLabel1;
    }

    public void setjLabel1(JLabel jLabel1) {
        this.jLabel1 = jLabel1;
    }

    public JLabel getjLabel2() {
        return jLabel2;
    }

    public void setjLabel2(JLabel jLabel2) {
        this.jLabel2 = jLabel2;
    }

    public JLabel getjLabel3() {
        return jLabel3;
    }

    public void setjLabel3(JLabel jLabel3) {
        this.jLabel3 = jLabel3;
    }

    public JLabel getjLabel4() {
        return jLabel4;
    }

    public void setjLabel4(JLabel jLabel4) {
        this.jLabel4 = jLabel4;
    }

    public JLabel getjLabel5() {
        return jLabel5;
    }

    public void setjLabel5(JLabel jLabel5) {
        this.jLabel5 = jLabel5;
    }

    public JLabel getjLabel6() {
        return jLabel6;
    }

    public void setjLabel6(JLabel jLabel6) {
        this.jLabel6 = jLabel6;
    }

    public JLabel getjLabel7() {
        return jLabel7;
    }

    public void setjLabel7(JLabel jLabel7) {
        this.jLabel7 = jLabel7;
    }

    public JTextField getQtdRegTXT() {
        return qtdRegTXT;
    }

    public void setQtdRegTXT(JTextField qtdRegTXT) {
        this.qtdRegTXT = qtdRegTXT;
    }

    public JTextField getSaveArquivoTXT() {
        return saveArquivoTXT;
    }

    public void setSaveArquivoTXT(JTextField saveArquivoTXT) {
        this.saveArquivoTXT = saveArquivoTXT;
    }

    public JTextField getSelArquivoTXT() {
        return selArquivoTXT;
    }

    public void setSelArquivoTXT(JTextField selArquivoTXT) {
        this.selArquivoTXT = selArquivoTXT;
    }

    public JTextField getTotalTXT() {
        return totalTXT;
    }

    public void setTotalTXT(JTextField totalTXT) {
        this.totalTXT = totalTXT;
    }

    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dataTXT;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JTextField qtdRegTXT;
    private javax.swing.JTextField saveArquivoTXT;
    private javax.swing.JTextField selArquivoTXT;
    private javax.swing.JTextField totalTXT;
    // End of variables declaration//GEN-END:variables
}
